﻿using Instagram.Version2.Helper;
using Instagram.Version2.Models;
using System.Collections;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace Instagram.Version2
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private UserModel _user;

        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void FillGallery(string userName)
        {
            var photos = await ApiCaller.GetAsync<IEnumerable<PhotoModel>>("api/Photos/GetUserPhotos?User=" + userName);

            if (photos == null)
                return;

            foreach (var photo in photos)
            {
                gallery.Children.Add(new TextBlock
                {
                    Text = "Title: " + photo.Title,
                    FontSize = 20
                });

                gallery.Children.Add(new TextBlock
                {
                    Text = "Created: " + photo.Created.ToString(),
                    FontSize = 20
                });

                var image = new Image()
                {
                    Source = Converter.GetImage(photo.Image),
                    Stretch = Stretch.Uniform,
                    Name = photo.Id.ToString()
                };

                image.Tapped += image_Tapped;

                gallery.Children.Add(image);
            }
        }

        void image_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            Frame.Navigate(typeof(PhotoDetails), (sender as Image).Name);
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _user = e.Parameter as UserModel;
            nickname.Text = _user.Name;

            FillGallery(_user.Name);
        }

        private void NewPhoto_Click(object sender, RoutedEventArgs args)
        {
            Frame.Navigate(typeof(PhotoPage), _user);
        }

        private void Search_Click(object sender, RoutedEventArgs args)
        {
            Frame.Navigate(typeof(Search));
        }

        private void Latest_Click(object sender, RoutedEventArgs args)
        {
            Frame.Navigate(typeof(LatestPhoto));
        }
    }
}
